/**
 * Copyright &copy; 2012-2016 <a href="https://istep.lczyfz.com">Istep</a> All rights reserved.
 */
package com.lczyfz.istep.modules.race.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lczyfz.istep.modules.race.dao.RaceScheduleTeamSubjectDao;
import com.lczyfz.istep.modules.race.entity.RaceRepertory;
import com.lczyfz.istep.modules.race.service.RaceTeamScoreService;
import com.sun.org.apache.bcel.internal.generic.I2F;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.lczyfz.istep.common.config.Global;
import com.lczyfz.istep.common.persistence.Page;
import com.lczyfz.istep.common.web.BaseController;
import com.lczyfz.istep.common.utils.StringUtils;
import com.lczyfz.istep.modules.race.entity.RaceSchedule;
import com.lczyfz.istep.modules.race.service.RaceScheduleService;


import java.text.*;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 赛程管理Controller
 * @author CY
 * @version 2017-04-26
 */
@Controller
@RequestMapping(value = "${adminPath}/race/raceSchedule")
public class RaceScheduleController extends BaseController {

	@Autowired
	private RaceScheduleService raceScheduleService;
	@Autowired
	private RaceTeamScoreService raceTeamScoreService;
	@Autowired
	RaceScheduleTeamSubjectDao raceScheduleTeamSubjectDao;


	@ModelAttribute
	public RaceSchedule get(@RequestParam(required = false) String id) {
		RaceSchedule entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = raceScheduleService.get(id);
		}
		if (entity == null) {
			entity = new RaceSchedule();
		}
		return entity;
	}

	@RequiresPermissions("race:raceSchedule:view")
	@RequestMapping(value = {"list", ""})
	public String list(RaceSchedule raceSchedule, HttpServletRequest request, HttpServletResponse response, Model model, String schedule_closeId) {
		Page<RaceSchedule> page = raceScheduleService.findPage(new Page<RaceSchedule>(request, response), raceSchedule);
		model.addAttribute("page", page);

//		获取开启过的赛程的id和状态
		RaceSchedule raceSchedule1 = raceScheduleService.scheduleStatus();
		if (raceSchedule1 != null) {
			String aid = raceSchedule1.getId();
			String status = raceSchedule1.getScheduleStatus();
			System.err.println("status---" + status);
			model.addAttribute("state1", status);
			model.addAttribute("sid", aid);
		} else {
			model.addAttribute("sid", schedule_closeId);
			model.addAttribute("state1", "0");
		}

		return "modules/race/raceScheduleList";
	}

	@RequiresPermissions("race:raceSchedule:view")
	@RequestMapping(value = "form")
	public String form(RaceSchedule raceSchedule, Model model) {
		model.addAttribute("raceSchedule", raceSchedule);
		List<RaceRepertory> raceRepertories = raceScheduleService.findRepertory();
		model.addAttribute("raceRepertories", raceRepertories);
		model.addAttribute("copy", null);
		return "modules/race/raceScheduleForm";
	}


	@RequiresPermissions("race:raceSchedule:view")
	@RequestMapping(value = "formCopy")
	public String formCopy(RaceSchedule raceSchedule, Model model) {
		raceSchedule.setScheduleName(raceSchedule.getScheduleName() + "-副本");
		model.addAttribute("raceSchedule", raceSchedule);
		List<RaceRepertory> raceRepertories = raceScheduleService.findRepertory();
		model.addAttribute("raceRepertories", raceRepertories);
		model.addAttribute("copy", "copy");
		return "modules/race/raceScheduleForm";
	}

	@RequiresPermissions("race:raceSchedule:edit")
	@RequestMapping(value = "save")
	public String save(RaceSchedule raceSchedule, Model model, RedirectAttributes redirectAttributes, String topy) {

		if (!beanValidator(model, raceSchedule)) {
			return form(raceSchedule, model);
		}

		if (topy != null && topy.equals("topy")) {
			raceSchedule.setId(null);
		}
		if (null == raceSchedule.getPlusReluI() || raceSchedule.getPlusReluI().equals("")) {
			raceSchedule.setPlusReluI("0");
		}
		if (null == raceSchedule.getPlusReluIi() || raceSchedule.getPlusReluIi().equals("")) {
			raceSchedule.setPlusReluIi("0");
		}

		if (null == raceSchedule.getPlusReluIii() || raceSchedule.getPlusReluIii().equals("")) {
			raceSchedule.setPlusReluIii("0");
		}

		if (null == raceSchedule.getPlusReluIv() || raceSchedule.getPlusReluIv().equals("")) {
			raceSchedule.setPlusReluIv("0");
		}

		if (null == raceSchedule.getPlusReluV() || raceSchedule.getPlusReluV().equals("")) {
			raceSchedule.setPlusReluV("0");
		}

		if (raceSchedule.getBeginTime().after(new Date())) {
			addMessage(redirectAttributes, "赛程开启时间不能大于当前时间 ！保存失败！");
			return "redirect:" + Global.getAdminPath() + "/race/raceSchedule";
		} else if (raceSchedule.getEndTime().before(new Date())) {
			addMessage(redirectAttributes, "赛程结束时间不能小于当前时间！保存失败！");
			return "redirect:" + Global.getAdminPath() + "/race/raceSchedule";
		} else if (raceSchedule.getBeginTime().after(raceSchedule.getEndTime())) {
			addMessage(redirectAttributes, "赛程结束时间不能小于开启时间！保存失败！");
			return "redirect:" + Global.getAdminPath() + "/race/raceSchedule";
		}

		raceSchedule.setScheduleStatus("0");
		raceScheduleService.save(raceSchedule);
		addMessage(redirectAttributes, "保存赛程成功");
		return "redirect:" + Global.getAdminPath() + "/race/raceSchedule/?repage";
	}


	//延长比赛时间
	@RequiresPermissions("race:raceSchedule:edit")
	@RequestMapping(value = "overtime")
	public String overtime(String time, String timeId, RedirectAttributes redirectAttributes) {

		if (time != null && !time.equals("")) {
			int time1 = Integer.parseInt(time);
			RaceSchedule raceSchedule = raceScheduleService.teamDetails(timeId);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String begin = sdf.format(raceSchedule.getBeginTime());
			String end = sdf.format(raceSchedule.getEndTime());
			try {
				Date beginTime = sdf.parse(begin);
				Date endTime = sdf.parse(end);
				Long minutes = (endTime.getTime() - beginTime.getTime()) / (1000 * 60);
				Long minutes1 = endTime.getTime() - beginTime.getTime();
				Long a = beginTime.getTime() + minutes1 + (time1 * 1000 * 60);
				Date date1 = new Date(a);
				String end1 = sdf.format(date1);
				Date date = sdf.parse(end1);
				raceSchedule.setEndTime(date);
				raceScheduleService.save(raceSchedule);

			} catch (ParseException e) {
				e.printStackTrace();
			}
		}


		RaceSchedule raceSchedule = raceScheduleService.teamDetails(timeId);
		if (raceSchedule.getScheduleStatus() != null && raceSchedule.getScheduleStatus().equals("1")) {
			if (raceScheduleService.t != null) {
				raceScheduleService.t.cancel();
				raceScheduleService.timeValue = 0;
			}
			//计数开始到比赛结束的时间
			int a = 0;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String begin = sdf.format(new Date());

			String end = sdf.format(raceSchedule.getEndTime());
			try {
				Date beginTime = sdf.parse(begin);
				Date endTime = sdf.parse(end);
				long minutes = (endTime.getTime() - beginTime.getTime()) / 1000;
				a = (int) minutes;
			} catch (ParseException e) {
				e.printStackTrace();
			}
			raceScheduleService.time(a);
			addMessage(redirectAttributes, raceSchedule.getScheduleName() + "， 延长时间成功");
		}


		return "redirect:" + Global.getAdminPath() + "/race/raceSchedule/?repage";
	}


	@RequiresPermissions("race:raceSchedule:edit")
	@RequestMapping(value = "delete")
	public String delete(RaceSchedule raceSchedule, RedirectAttributes redirectAttributes) {

		if (raceSchedule.getScheduleStatus().equals("1")) {
			addMessage(redirectAttributes, "删除失败，请先停止该赛程");
			return "redirect:" + Global.getAdminPath() + "/race/raceSchedule/?repage";
		}

		raceScheduleService.delete(raceSchedule);
		addMessage(redirectAttributes, "删除赛程成功");
		return "redirect:" + Global.getAdminPath() + "/race/raceSchedule/?repage";
	}


	@RequiresPermissions("race:raceSchedule:edit")
	//@ResponseBody
	@RequestMapping(value = "state")
	public String state(String id, String status, String count, RedirectAttributes redirectAttributes, HttpServletRequest request, HttpServletResponse response, Model model) {

		System.err.println("id--------------" + id);
		RaceSchedule raceSchedule1 = new RaceSchedule();


		if (status.equals("0")) {

        raceScheduleService.cleanData();

			RaceLoginController.number = 0;
			Page<RaceSchedule> page = raceScheduleService.findPage(new Page<RaceSchedule>(request, response), raceSchedule1);
			for (RaceSchedule raceSchedule2 : page.getList()) {
				raceSchedule2.setScheduleStatus("0");
				raceScheduleService.save(raceSchedule2);
			}

			RaceSchedule raceSchedule = raceScheduleService.teamDetails(id);
			System.out.println(raceSchedule.getEndTime());
			System.out.println(new Date());
			if (raceSchedule.getEndTime().before(new Date())) {
				addMessage(redirectAttributes, "该赛程已结束！开启失败！");
				return "redirect:" + Global.getAdminPath() + "/race/raceSchedule?status1=3";

			}

			raceSchedule.setScheduleStatus("1");
			raceScheduleService.save(raceSchedule);

			if (RaceLoginController.flags != null) {
//				System.out.println("------进入"+RaceLoginController.flags);
				RaceLoginController.flags.removeAll(RaceLoginController.flags);
			}
			raceScheduleTeamSubjectDao.finish();
			raceSchedule.setScheduleStatus("1");

			if (raceScheduleService.t != null) {
				raceScheduleService.t.cancel();
				raceScheduleService.timeValue = 0;
			}
			if (raceScheduleService.t1 != null) {
				raceScheduleService.t1.cancel();
				raceScheduleService.timeValue1 = 0;
				raceScheduleService.ti = 0;
			}

//拿到开启的时间跟当前的时间还有多久

			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
			String date1 = df.format(new Date());
			String begin1 = df.format(raceSchedule.getBeginTime());
			int minutes1 = 0;
			try {
				Date beginTime = df.parse(date1);
				Date endTime = df.parse(begin1);
				long minutes = (endTime.getTime() - beginTime.getTime()) / 1000;
				minutes1 = (int) minutes;
			} catch (ParseException e) {
				e.printStackTrace();
			}

//----------------------------------------------


			//计数开始到比赛结束的时间
			int a = 0;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

//			String begin = sdf.format(raceSchedule.getBeginTime());
			String begin = df.format(new Date());


			String end = sdf.format(raceSchedule.getEndTime());
			try {
				Date beginTime = sdf.parse(begin);
				Date endTime = sdf.parse(end);
				long minutes = (endTime.getTime() - beginTime.getTime()) / 1000;
				a = (int) minutes;
			} catch (ParseException e) {
				e.printStackTrace();
			}
			if (minutes1 <= 0) {
				raceScheduleService.save(raceSchedule);
				raceScheduleService.time(a);
			} else {
				raceScheduleService.time1(minutes1, raceSchedule, a);

			}


			addMessage(redirectAttributes, raceSchedule.getScheduleName() + "， 开启成功");

			System.out.println("启动分数计数定时");

			try {
				System.out.println("展示粒度" + raceSchedule.getDisplaySize());
				raceTeamScoreService.instanceScheduleJob(raceSchedule, raceSchedule.getDisplaySize());
			} catch (Exception e) {
				e.printStackTrace();
			}

			model.addAttribute("state1", "1");
		}


		if (status.equals("1")) {
			RaceLoginController.number = 0;
			RaceSchedule raceSchedule = raceScheduleService.teamDetails(id);
			if (raceSchedule.getScheduleStatus().equals("0")) {
//				addMessage(redirectAttributes, "该赛程已关闭");
				return "redirect:" + Global.getAdminPath() + "/race/raceSchedule?status1=3";
			}

			if (raceScheduleService.t != null) {
				raceScheduleService.t.cancel();
				raceScheduleService.timeValue = 0;
			}
			if (raceScheduleService.t1 != null) {
				raceScheduleService.t1.cancel();
				raceScheduleService.timeValue1 = 0;
				raceScheduleService.ti = 0;
			}

			if (RaceLoginController.flags != null) {
				RaceLoginController.flags.removeAll(RaceLoginController.flags);
			}

			raceSchedule.setScheduleStatus("0");
			raceScheduleService.save(raceSchedule);
			addMessage(redirectAttributes, raceSchedule.getScheduleName() + "， 已关闭");

			try {
				raceTeamScoreService.deleteScheduleJob(raceSchedule);
			} catch (Exception e) {
				e.printStackTrace();
			}
			model.addAttribute("state1", "0");
		}


		return "redirect:" + Global.getAdminPath() + "/race/raceSchedule/?repage&status=" + status + "&schedule_closeId=" + id;
	}


	@ResponseBody
	@RequestMapping(value = "teamDetails")
	public RaceSchedule teamDetails(String uid) {
		return raceScheduleService.teamDetails(uid);
	}


	@ResponseBody
	@RequestMapping(value = "startTheTime")
	public int startTheTime(String id) {
		int a = 0;
		RaceSchedule raceSchedule = raceScheduleService.teamDetails(id);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String begin = sdf.format(raceSchedule.getBeginTime());
		String end = sdf.format(raceSchedule.getEndTime());
		try {
			Date beginTime = sdf.parse(begin);
			Date endTime = sdf.parse(end);
			long minutes = (endTime.getTime() - beginTime.getTime()) / 1000;
			a = (int) minutes;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return a;
	}
}